import logging
from math import e

from .models import Room,Order,Order_Detail
from account.models import UserProfile
from django.contrib.auth.models import User
from .serializers import RoomListSerializer
from rest_framework.response import Response
from django.db.models import F
from django.core.exceptions import ObjectDoesNotExist,RequestAborted
from django.http import JsonResponse
import random
from django.db.models import Q
from rest_framework.response import Response
import json
import time
from django.views.decorators.http import require_http_methods
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer

logger = logging.getLogger(__name__)

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def room_list(request):
    if request.method == 'GET':
        rooms = Room.objects.all()
        serializer = RoomListSerializer(rooms, many=True)
        return JsonResponse(serializer.data,safe=False)

@require_http_methods(['POST'])
def select_room(request):
    data = json.loads(request.body)
    mate1 = data['roommate1']
    mate2 = data['roommate2']
    mate3 = data['roommate3']
    select = data['select']
    count = 1
    if mate1 != '':
        if not User.objects.filter(username = mate1):
            raise ObjectDoesNotExist('同住人1不存在')
        count+=1
    if mate2 != '':
        if not User.objects.filter(username = mate2):
            raise ObjectDoesNotExist('同住人2不存在')
        count+=1
    if mate3 != '':
        if not User.objects.filter(username = mate3):
            raise ObjectDoesNotExist('同住人3不存在')
        count+=1
    username = request.user['data']['username']
    user = User.objects.filter(username = username).first()
    userprofile = UserProfile.objects.get(user = user)
    if Order.objects.filter(user = user): ##判断用户是否已经提交过订单
        raise RequestAborted('已经提交过订单')
    if not userprofile: ##判断用户是否填写自己的个人信息
        raise ObjectDoesNotExist('未填写个人信息')
    gender = userprofile.gender
    if not Room.objects.filter(Q(unit_id = select) & Q(gender=gender)).exists(): ##判断选择的单元是否符合用户性别
        raise RequestAborted('该单元不符合你的性别')
    if not Room.objects.filter(Q(unit_id = select) & Q(avail_bed__gte=count)).exists(): ##判断该单元是否有空床
        raise ObjectDoesNotExist('该单元空床不足')
    rooms = Room.objects.filter(Q(unit_id = select) & Q(avail_bed__gte=count))
    room_num = len(rooms)
    random_index = random.randint(0,room_num-1) ##从符合条件的房间里随机选择一个
    selected = rooms[random_index]
    roomID = selected.room_id
    Room.objects.filter(room_id = roomID).update(avail_bed = F('avail_bed') - count) ##选择成功后更新空床数
    Order.objects.create(user = user,unit_id = selected.unit_id, num_of_stu = count, success = 1, submit_time = time.time(), gender = gender) ##选择有效就创建订单
    order = Order.objects.filter(user = user).first()
    if count == 1:
        Order_Detail.objects.create(order = order)
    if count == 2:
        Order_Detail.objects.create(order = order,roommate1 = mate1)
    if count == 3:
        Order_Detail.objects.create(order = order,roommate1 = mate1, roommate2 = mate2)
    if count == 4:
        Order_Detail.objects.create(order = order,roommate1 = mate1, roommate2 = mate2, roommate3 = mate3)
    return JsonResponse({'status': True, '房间号' : selected.room_id})